/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.hugo.senai.dao;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import javax.swing.JOptionPane;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

/**
 * Hibernate Utility class with a convenient method to get Session Factory
 * object.
 *
 * @author alunoo
 */
public class HibernateUtil {

    private static final SessionFactory sessionFactory;

    //
    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) 
            // config file.
            //FileReader leitor =new FileReader(new File("config.txt"));
            Path path = Paths.get("config.txt");
            List <String> linhas = Files.readAllLines(path, StandardCharsets.UTF_8);

            String senha = "";
            String usuario = "";
            String url = "";

            for (String a : linhas) {

                String[] split = a.split(";");
                url = split[0];
                usuario = split[1];
                senha = split[2];

            }
            sessionFactory = new AnnotationConfiguration().configure().setProperty("hibernate.connection.password", senha).setProperty("hibernate.connection.username", usuario).setProperty("hibernate.connection.url", url).
                    buildSessionFactory();
        } catch (Exception ex) {

            JOptionPane.showMessageDialog(null, "FALHA AO INICIAR O BANCO", "erro", JOptionPane.ERROR_MESSAGE);

            // System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);

        }
    }

    public static SessionFactory getSessionFactory() {

        return sessionFactory;
    }
    
    
    public static void close(){
        getSessionFactory().close();
    }

}
